package br.usp.poli.csv;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import br.usp.poli.entity.DataSetMetadata;
import br.usp.poli.entity.Experiment;
import br.usp.poli.entity.Occurrence;
import br.usp.poli.entity.Variable;
import br.usp.poli.util.db.HibernateUtil;

import com.ricebridge.csvman.CsvManager;

/**
 * @author Leonardo Bessa
 * 
 */
public class CSVFactory {

	@SuppressWarnings("unchecked")
	public static void createCSV(Experiment experiment) {
		CsvManager csvManager = new CsvManager();
		csvManager.setCsvSpec(CsvManager.makeExcelSpec());
		List<Variable> variables = experiment.getVariables();

		Session session = HibernateUtil.getSession();
		DataSetMetadata dataSetMetadata = experiment.getDataSetMetadata();
		GregorianCalendar startDate = dataSetMetadata.getStartDate();
		GregorianCalendar endDate = dataSetMetadata.getEndDate();
		Criteria criteria = session.createCriteria(Occurrence.class).add(
				Restrictions.between("date", startDate, endDate)).add(
						Restrictions.in("variable", variables))
						.addOrder(Order.asc("date"));
		List<Occurrence> occurrences = criteria.list();
		List<List<String>> data = new ArrayList<List<String>>();
		List<String> headers = new ArrayList<String>();
		headers.add("Date");
		for (Variable variable : variables) {
			headers.add(variable.toString());
		}
		data.add(headers);
		GregorianCalendar lastDate = null;
		List<String> lastLine = null;
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		for (Occurrence occurrence : occurrences) {
			GregorianCalendar occurenceDate = occurrence.getDate();
			if (occurenceDate.equals(lastDate)){
				lastLine.set(variables.indexOf(occurrence.getVariable())+1, occurrence.getValue());
			}else{
				lastDate = occurenceDate;
				lastLine = new ArrayList<String>(variables.size()+1);
				lastLine.add(format.format(occurenceDate.getTime()));
				for (@SuppressWarnings("unused")
				Variable variable : variables) {
					lastLine.add(variable.getMissingCodeValue());
				}
				lastLine.set(variables.indexOf(occurrence.getVariable())+1, occurrence.getValue());
				data.add(lastLine);
			}
		}
		
		csvManager.saveAsLists("weblab-exported.csv", data);
	}

}
